#!usr/bin/node

const http = require('http');

let items = [];

http.createServer((req,res) => {
  console.log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  console.log(items);
  switch(req.method) {
    case 'GET':
      select(req,res);
      break;
    case 'POST':
      insert(req,res);
      break;
    case 'DELETE':
      del(req,res);
      break;
    case 'PUT':
      update(req,res);
      break;
    default:
      res.end('request method not support!');
  }
}).listen(8080);

function select(req,res) {
  res.setHeader('Access-Control-Allow-Origin','*');
  res.statusCode = 200;
  res.end(JSON.stringify(items));
}

function insert(req,res) {
  res.setHeader('Access-Control-Allow-Origin','*');
  let item = '';
  req.on('data',chunk => {
    item += chunk;
  });
  console.log(item);
  req.on('end',() => {
    if(item !== '' || typeof item !== 'undefined') {
      items.push(item);
      res.statusCode = 200;
      res.end('insert ok!');
    }else {
      res.statusCode = 400;
      res.end('item empty');
    }
  })
}

function del(req,res) {
  res.setHeader('Access-Control-Allow-Origin','*');
  
  if(req.url === '/') {
    items = [];
    res.end('delete ok!');
    return ;
  }

  const arg = req.url.split(':'),
        id = parseInt(arg[1]);

  if(!items[id]) {
    res.statusCode = 404;
    res.end('not found!');
  }else{
    items.splice(id,1);
    res.statusCode = 200;
    res.end('delete ok!');
  }
}

function update(req,res) {
  res.setHeader('Access-Control-Allow-Origin','*');

  const arg = req.url.split(':'),
        id = parseInt(arg[1]);

  let item = '';

  req.on('data',chunk => {
    item += chunk;
  });
  req.on('end',() => {
    if(!items[id]) {
      res.statusCode = 404;
      res.end('not found!');
    }else{
      items[id] = item;
      res.statusCode = 200;
      res.end('update  ok!');
    }
  })
}
